/*
 * Lenovo Group
 * Copyright (c) 2015-2016 All Rights Reserved.
 * 
 * Project Name:assign-tracer
 * Create Time: 2016年1月21日 下午3:46:04
 */
package com.lenovo.lmrp.server.assigntracer.util.pusher;

import java.util.regex.Pattern;

import javax.inject.Inject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.lenovo.sdc.framework.sns.ASMSRequest.ContentType;
import com.lenovo.lmrp.server.assigntracer.scheduler.RetryPushMessageTask;
import com.lenovo.sdc.framework.mq.AMQClient;
import com.lenovo.sdc.framework.scheduler.ScheduleTaskManager;
import com.lenovo.sdc.framework.sns.SMSHttpClient;
import com.lenovo.sdc.framework.util.AttributeBean;
import com.lenovo.sdc.framework.util.CommonUtil;
import com.lenovo.sdc.framework.util.exception.ErrorCode;
import com.lenovo.sdc.framework.util.exception.TraceableException;

/**
 * @author songyz
 *
 */
public class SMSSender implements ISender {

    private static final Logger logger = LoggerFactory.getLogger(SMSSender.class);
    private static final Pattern PHONE_PATTERN = Pattern
        .compile("^((13[0-9])|(15[^4,\\D])|(17[0-9])|(18[0-9]))\\d{8}$");

    //	private LinkedList<PushParameter> pushParameterList = new LinkedList<PushParameter>();

    private AttributeBean params;
    private SMSHttpClient smsHttpClient;
    private AMQClient mqClient;

    @Inject
    public void set(AMQClient mqClient) {
        this.mqClient = mqClient;
    }

    @Inject
    public void set(AttributeBean params) {
        this.params = params;
    }

    @Inject
    public SMSSender(AttributeBean params) {
        this.params = params;
        String proxyHost = params.getAttribute("http.proxy.ip", "");
        String proxyPort = params.getAttribute("http.proxy.port", "");
        String proxy = null;
        if (CommonUtil.nonNullAndEmpty(proxyHost) && CommonUtil.nonNullAndEmpty(proxyPort)) {
            proxy = proxyHost + ":" + proxyPort;
        }
        smsHttpClient = new SMSHttpClient(params.getAttribute("short.host", ""), proxy);
    }

    public void SendMessage(PushParameter pushParameter) {
        String mobile = pushParameter.getMobile();
        if (CommonUtil.isNullOrEmpty(mobile) || PHONE_PATTERN.matcher(mobile).matches() == false) {
            logger.warn("SMSSender send faild. Because the parameter is wrong. mobile is :[{}]. engineerid is:[{}]",
                mobile, pushParameter.getEngineerId());
            return;
        }
        SMSResponseImpl smsResponseImpl = new SMSResponseImpl();
        try {
            SMSRequestImpl smsRequestImpl = new SMSRequestImpl(ContentType.XML,
                params.getAttribute("short.username", "gaoyi4"), params.getAttribute("short.password", "gaoyi4"),
                mobile, pushParameter.getContent());
            smsHttpClient.sendSMS(smsRequestImpl, smsResponseImpl);
            if (smsResponseImpl.getStuats() == 0) {
                smsResponseImpl = smsResponseImpl.getBody();
                logger.info(
                    "SMSSender result engineerid is:[{}{}],resultCode:{},stateMessage:{},sendNumber:{},messageContent:{}",
                    pushParameter.getEngineerId(), pushParameter.getMobile(), smsResponseImpl.getResultCode(),
                    smsResponseImpl.getStateMessage(), smsResponseImpl.getSendNumber(), pushParameter.getContent());
                if ("调用成功，短信已发送".equals(smsResponseImpl.getStateMessage())
                    && "00".equals(smsResponseImpl.getResultCode())) {
                    sendMQMessage(mqClient, pushParameter, SendResult.SEND_SUCCEED.getResult());
                }
                else {
                    this.retryPushMessage(pushParameter);
                }
            }
            else {
                this.retryPushMessage(pushParameter);
            }
        }
        catch (Exception e) {
            throw new TraceableException(ErrorCode.COMM_PARSE_FAILED, e);
        }
    }

    /**
     * 短信失败重发
     * @param pushParameter
     */
    @Override
    public void retryPushMessage(PushParameter pushParameter) {
        logger.warn("SMSSender failed. engineer is {},mobile is {},content is {}", pushParameter.getEngineerId(),
            pushParameter.getMobile(), pushParameter.getContent());
        sendMQMessage(mqClient, pushParameter, SendResult.SEND_FAILD.getResult());
        RetryPushMessageTask retrySMSMessageTask = new RetryPushMessageTask(pushParameter, params);
        ScheduleTaskManager.getDefaultSchduler().scheduleTask(retrySMSMessageTask);
    }

    //	public void run() {
    //		PushParameter pushParameter = this.pushParameterList.getFirst();
    //		this.pushParameterList.removeFirst();
    //		SendMessage(pushParameter);
    //	}

    public Runnable addMessageToList(PushParameter msParameter) {
        //		this.pushParameterList.addLast(msParameter);
        logger.debug("create task engineer{}, phone{}", msParameter.getEngineerId(), msParameter.getMobile());
        return new pushMessage(msParameter);
    }

    private class pushMessage implements Runnable {

        private PushParameter msParameter;

        public pushMessage(PushParameter msParameter) {
            this.msParameter = msParameter;
        }

        @Override
        public void run() {
            logger.debug("begin run task engineer{}, phone{}", msParameter.getEngineerId(), msParameter.getMobile());
            SendMessage(msParameter);
        }
    }
}
